﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FyndSharp.Utilities.Common;
using System.Web.Script.Serialization;
using Fynd.Hermes.Web.Objects;

namespace Fynd.Hermes.Web.Pages
{
    public abstract class AjaxHandlerPage : RoleBasedPage
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (true == TryHandleAjaxRequest())
            {
                try
                {
                    Response.End();
                }
                catch { }
            }
        }

        private bool TryHandleAjaxRequest()
        {
            if (TypeConvert.ToBool(Request.QueryString["ajax"]) == true)
            {
                object result = null;
                try
                {
                    result = HandleAjaxRequest();
                
                    if (null != result)
                    {
                        JavaScriptSerializer serializer = new JavaScriptSerializer();
                        string resultJson = String.Empty;
                        try
                        {
                            serializer.Serialize(result);
                        }
                        catch(Exception e)
                        {
                            throw new AjaxException("Server application internal error, the result object can not be serialized.", e);
                        }
                    }
                }
                catch (AjaxException e1)
                {
                    Response.StatusCode = 500;
                    Response.Write(e1.Message);
                }
                return true;
            }
            return false;
        }

        

        protected abstract object HandleAjaxRequest();
    }
}